//********ku9 js直播源代理脚本********//
// 文件名：kzb.js
// 使用方法：http://您的域名/ku9/js/kzb.js?id=cctv1&fmt=hls

// 频道ID映射表
const channelMap = {
    "cctv1": 578, "cctv2": 579, "cctv3": 580, "cctv4": 581, "cctv4a": 595, "cctv4o": 596,
    "cctv5": 582, "cctv5p": 583, "cctv6": 584, "cctv7": 585, "cctv8": 586, "cctv9": 587,
    "cctv10": 588, "cctv11": 589, "cctv12": 590, "cctv13": 591, "cctv14": 592, "cctv15": 593,
    "cctv17": 594, "bjws": 608, "dfws": 597, "tjws": 611, "cqws": 607, "hljws": 621,
    "jlws": 601, "lnws": 620, "gsws": 622, "qhws": 605, "sxws": 603, "hbws": 615,
    "sdws": 613, "ahws": 612, "hnws": 616, "hubws": 604, "hunws": 609, "jxws": 602,
    "jsws": 599, "zjws": 617, "dnws": 618, "gdws": 598, "szws": 606, "gxws": 614,
    "gzws": 619, "scws": 610, "xjws": 623, "btws": 624, "hinws": 600
};

// 主函数
function main(item) {
    // 获取请求参数
    const url = item.url;
    const id = ku9.getQuery(url, "id") || "cctv1";
    const fmt = ku9.getQuery(url, "fmt") || "hls";
    
    // 检查频道是否存在
    const channelId = channelMap[id];
    if (!channelId) {
        return JSON.stringify({ error: "频道不存在或暂时不可用" });
    }
    
    // 尝试从缓存获取API数据
    const cacheKey = "iptv_list_cache";
    const cacheData = ku9.getCache(cacheKey);
    let data = null;
    
    if (cacheData && ku9.isJsonObject(cacheData)) {
        data = JSON.parse(cacheData);
        // 检查缓存时间（30分钟有效期）
        const cacheTime = data.cacheTime || 0;
        if (Date.now() - cacheTime < 30 * 60 * 1000) {
            // 缓存有效，使用缓存数据
            const streamUrl = findStreamUrl(data.list, channelId, fmt);
            if (streamUrl) {
                return JSON.stringify({ url: streamUrl });
            }
        }
    }
    
    // 缓存无效或不存在，重新获取API数据
    const apiUrl = "https://jzb123.huajiaedu.com/prod-api/iptv/getIptvList?liveType&deviceType=1";
    const headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"
    };
    
    try {
        const response = ku9.get(apiUrl, headers);
        
        if (response && ku9.isJsonObject(response)) {
            data = JSON.parse(response);
            
            // 保存到缓存（包含时间戳）
            data.cacheTime = Date.now();
            ku9.setCache(cacheKey, JSON.stringify(data), 30 * 60 * 1000); // 30分钟缓存
            
            const streamUrl = findStreamUrl(data.list, channelId, fmt);
            if (streamUrl) {
                return JSON.stringify({ url: streamUrl });
            }
        }
    } catch (error) {
        // API请求失败，尝试使用旧缓存
        if (data) {
            const streamUrl = findStreamUrl(data.list, channelId, fmt);
            if (streamUrl) {
                return JSON.stringify({ url: streamUrl });
            }
        }
    }
    
    return JSON.stringify({ error: "频道不存在或暂时不可用" });
}

// 查找流地址函数
function findStreamUrl(channelList, channelId, fmt) {
    if (!channelList || !Array.isArray(channelList)) {
        return null;
    }
    
    for (const channel of channelList) {
        if (channel.id === channelId && channel.play_source_url) {
            let streamUrl = channel.play_source_url;
            
            // HTTPS转HTTP
            streamUrl = streamUrl.replace(/^https:/, 'http:');
            
            // 格式转换
            if (fmt === 'flv') {
                streamUrl = streamUrl.replace(/\.m3u8$/, '.flv');
            }
            
            return streamUrl;
        }
    }
    
    return null;
}

// 辅助函数：获取所有频道列表（可用于EPG配置）
function getChannelList() {
    const channelList = [];
    for (const [key, value] of Object.entries(channelMap)) {
        channelList.push({
            name: key,
            id: value,
            url: `http://您的域名/ku9/js/kzb.js?id=${key}&fmt=hls`
        });
    }
    return channelList;
}

// 返回播放地址示例
function getExampleUrl() {
    const id = "cctv1";
    const fmt = "hls";
    return `http://您的域名/ku9/js/kzb.js?id=${id}&fmt=${fmt}`;
}